package com.atguigu.netty.group.chat.client;

import com.alibaba.fastjson.JSON;
import com.atguigu.netty.group.chat.model.MsgDTO;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

@Slf4j
public class ChatClient {

    public static void main(String[] args) throws InterruptedException {
        log.info("请输入昵称：");
        Scanner scanner = new Scanner(System.in);
        String userName = scanner.nextLine();
        log.info("你好,{},欢迎进入netty群聊。。。",userName);
        // 事件循环组
        NioEventLoopGroup eventExecutors = new NioEventLoopGroup();
        // 客户端启动对象
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(eventExecutors)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChatClientHandler(userName));
                    }
                });

        ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 8848).sync();
        log.info("请输入消息：");
        while (scanner.hasNextLine()) {
            String msg = scanner.nextLine();
            String jsonMsg = JSON.toJSONString(new MsgDTO(userName, msg));
            channelFuture.channel().writeAndFlush(Unpooled.copiedBuffer(jsonMsg, CharsetUtil.UTF_8));
        }
        channelFuture.channel().closeFuture().sync();
    }
}
